package com.atguigu.InternetCoding.chats;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @author zeng
 * @data 2021/06/30 9:37
 */
public class Sendtalk implements Runnable{
    private DatagramSocket socket;
    private String name;
    private int port;
    private int toport;
    private InetAddress add;

    public Sendtalk(String name, int port, int toport, String add) {
        this.name = name;
        this.port = port;
        this.toport = toport;
        try {
            this.add = InetAddress.getByName(add);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //建立一个UDP对象,可以不填写端口号，但接收的一端必须开放端口号
        try {
            this.socket = new DatagramSocket(this.port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        //设置数据报
        while (true) {
            Scanner sc = new Scanner(System.in);
            String s = sc.nextLine();
            if("eye".equals(s)){
                break;
            }
            String str = this.name + ":" + s;
            DatagramPacket packet = new DatagramPacket(str.getBytes(),0,str.getBytes().length, this.add,this.toport);
            //发送数据
            try {
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
